﻿//using BackData;
//using MediatR;
//using Microsoft.IdentityModel.Protocols.OpenIdConnect;
//using Server.API.Application.Command;
//using System.IdentityModel.Tokens.Jwt;

//namespace Server.API.Application.Handler
//{

//    public class NewTokenHandler:IRequestHandler<NewTokenCommand,APIResult<string>>
//    {
//        private readonly ILogger<NewTokenHandler> log;
//        private readonly TokenService tokenService;
//        private readonly IHttpContextAccessor httpContextAccessor;

//        public NewTokenHandler(ILogger<NewTokenHandler> log,IConfiguration configuration, TokenService tokenService,IHttpContextAccessor httpContextAccessor)
//        {
//            this.log = log;
//            this.tokenService = tokenService;
//            this.httpContextAccessor = httpContextAccessor;
//        }
//        /// <summary>
//        /// 刷新Token
//        /// </summary>
//        /// <param name="request">长期Token</param>
//        /// <param name="cancellationToken">取消</param>
//        /// <returns>新的Token</returns>
//        /// <exception cref="NotImplementedException"></exception>
//        public Task<APIResult<string>> Handle(NewTokenCommand request, CancellationToken cancellationToken)
//        {
//            APIResult<string> res = new APIResult<string>();
//            try
//            {
//                // 验证传入的Refresh Token是否有效
//                var isValid = tokenService.ValidateJwtToken(request.OldToken);
//                var username = httpContextAccessor.HttpContext?.User.Claims?.FirstOrDefault(x => x.Type == "UserName")?.Value ?? "管理员";
//                var realname = httpContextAccessor.HttpContext?.User.Claims?.FirstOrDefault(x => x.Type == "RealName")?.Value ?? "管理员";
//                if (isValid)
//                {
//                    // 使用Refresh Token换取新的Access Token
//                    res.Data = tokenService.ExchangeJwtToken(request.OldToken, username, realname);
//                    res.Num = StateCode.OK;
//                    res.Message = "刷新成功";
//                }
//                else
//                {
//                    res.Num = StateCode.Fail;
//                    res.Data = "登录已过期,请重新登录";
//                    res.Message = "登录已过期,请重新登录";
//                }
//                return Task.FromResult(res);
//            }
//            catch (Exception ex)
//            {
//                // 捕获所有异常，统一返回401
//                throw;
//            }
//        }
//    }
//}
   